package com.evaluationSystem.service.impl;

import com.alibaba.excel.EasyExcel;
import com.evaluationSystem.entity.Appraise;
import com.evaluationSystem.entity.Dimension;
import com.evaluationSystem.entity.Questionnaire;
import com.evaluationSystem.entity.User;
import com.evaluationSystem.entity.vo.QuestionnaireVo;
import com.evaluationSystem.entity.vo.UserVo;
import com.evaluationSystem.exception.EvaluationException;
import com.evaluationSystem.mapper.AppraiseMapper;
import com.evaluationSystem.mapper.DimensionMapper;
import com.evaluationSystem.service.DimensionService;
import com.evaluationSystem.util.CommonUtil;
import com.evaluationSystem.util.ExcelListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class DimensionImpl implements DimensionService {

    private final DimensionMapper dimensionMapper;
    private final AppraiseMapper appraiseMapper;

    @Override
    public List<Dimension> getDimension(String questionId) {
        return dimensionMapper.getDimension(questionId);
    }

    @Override
    public User findByUsername(String principal) {
        return dimensionMapper.findByUsername(principal);
    }

    @Override
    public List<Questionnaire> getQuestion(UserVo userVo) {
        return dimensionMapper.getQuestion(userVo.getQuestionList());
    }

    @Override
    public void insertDimension(Dimension dimension) {
        dimensionMapper.insertDimension(dimension);
    }
    @Override
    public void insertDimensions(Dimension dimension) {
        dimensionMapper.insertDimensions(dimension);
    }

    @Override
    public void insertBathDimension(List<Dimension> dimensionList) {
        dimensionMapper.insertBathDimension(dimensionList);
    }

    @Override
    public HashMap<String, Object> uploadDimension(MultipartFile multipartFile, String questionId) {
        CommonUtil.uploadExcel(multipartFile);
        ExcelListener listener = new ExcelListener();
        try {
            //注：headRowNumber默认为1，现赋值为2，即从第三行开始读取内容
            EasyExcel.read(multipartFile.getInputStream(), listener).headRowNumber(2).sheet().doRead();
        } catch (Exception e) {
            log.error("EasyExcel解析文件失败", e);
            throw new EvaluationException("文件解析失败，请重新上传");
        }
        //获取表头信息进行处理
        Map<Integer, String> headTitleMap = listener.getHeadTitleMap();
        //获取动态表头信息
        List<String> headList = headTitleMap.keySet().stream().map(key -> {
            String head = headTitleMap.get(key);
            log.info(head);
            return head;
        }).collect(Collectors.toList());//可以对表头进行入库保存，方便后续导出
        //数据行信息
        List<Map<Integer, Map<Integer, String>>> list = listener.getList();
        StringBuilder buffer = new StringBuilder();
        StringBuilder buffer2 = new StringBuilder();
        List<Object> resultList = new ArrayList<>();
        resultList.add(headList);
        int failCount = 0;//记录失败条数
        for (int i = 0; i < list.size(); i++) {
            String status = "0";
            for (int j = 0; j < list.get(i).get(i + 2).size(); j++) {
                if (list.get(i).get(i + 2).get(j) == null) {
                    status = "1";//0成功、1失败
                    resultList.add(list.get(i).get(i + 2));//存储失败的数据
                    failCount++;
                    break;
                }
            }
            list.get(i).get(i + 2).put(list.get(i).get(i + 2).size(), status);//0成功、1失败
            if (list.get(i).get(i + 2).get(list.get(i).get(i + 2).size() - 1).equals("1")) {
                continue;
            }
            for (int j = 2; j < headList.size(); j++) {
                String[] split = list.get(i).get(i + 2).get(j).split(",");
                buffer.append(split[0]).append(",");
                if (split.length > 1) {
                    buffer2.append(split[1]).append(",");
                } else {
                    buffer2.append(",");
                }
            }
            resultList.add(list.get(i).get(i + 2));//存储成功的数据
            String itemStr = buffer.substring(0, buffer.length() - 1);
            String itemStr2 = buffer2.substring(0, buffer2.length() - 1);
            Dimension dimension = new Dimension();
            dimension.setAssessDetail(list.get(i).get(i + 2).get(1));//题目
            dimension.setAssessItem(itemStr);//选项
            dimension.setAssessScore(itemStr2);//选项
            dimension.setQuestionId(questionId);
            dimension.setSort(i);
            buffer.delete(0, buffer.length());//清空buffer
            buffer2.delete(0, buffer2.length());//清空buffer
            dimensionMapper.insertDimension(dimension);//入库
        }

        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("sum", list.size());
        resultMap.put("success", list.size() - failCount);
        resultMap.put("fail", failCount);
        resultMap.put("detail", resultList);
        return resultMap;
    }

    @Override
    public void updateDimension(Dimension dimension) {
        dimensionMapper.updateDimension(dimension);
    }

    @Override
    public List<QuestionnaireVo> getQuestionList(User user) {
        List<QuestionnaireVo> list = dimensionMapper.getQuestionList(user);
        for (QuestionnaireVo questionnaireVo : list) {
            int appraiseNum = appraiseMapper.getScoreByName(user.getUsername(), null, questionnaireVo.getQuestionId());
            Appraise appraise = new Appraise();
            appraise.setAppraiserPhone(user.getUserId());
            appraise.setQuestionId(questionnaireVo.getQuestionId());
            int total = appraiseMapper.getAppraiseList(appraise).size();
            if (total != appraiseNum) {
                questionnaireVo.setAssessStatus(0);//0未评估 1已评估
            } else {
                questionnaireVo.setAssessStatus(1);
            }
        }
        return list;
    }

    @Override
    public void updateDimensionSort(List<Dimension> dimension) {
        Dimension oldDimension = dimension.get(0);
        Dimension newDimension = dimension.get(1);
        dimensionMapper.updateDimension(oldDimension);
        dimensionMapper.updateDimension(newDimension);
    }

    @Override
    public void deleteDimension(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        dimensionMapper.deleteDimension(map);
    }
}
